<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Buy extends La_Controller {
	
	function index() {
		if (!$this->authorize->is_logged_in()) {
			la_redirect('user/login?ref=' . urlencode(site_url('buy')), "请你先登录");
			die(0);
		}
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$this->load->model(array('Card_model', 'Order_model'));
			$count = $this->input->post("count");
			$other_count = $this->input->post("other_count");
			if (!empty($other_count)) $count = $other_count;
			if (empty($count)) {
				redirect("buy");die(0);
			}
			$current_user = $this->authorize->current_user();
			$order_data = array('created_by' => $current_user, 'amount' => '0.01' * $count, 'created' => date("Y-m-d H:i:s"));
			$order_id = $this->Order_model->add($order_data);
			for($i = 0; $i < $count; $i++) {
				$card_id = $this->Card_model->add();
				$this->Order_model->add_card_to_order($card_id, $order_id);
			}
			redirect("pay?order_id=" . $order_id);
		} else {
			$this->load->view('buy/by_alipay');
		}
		
	}
	/**
	 * 转让行动卡
	 */
	function transfer() {
		if (!$this->authorize->is_logged_in()) {
			la_redirect('user/login?ref=' . urlencode(site_url('buy/transfer')), "请你先登录");
			die(0);
		}
		$this->load->model(array('User_card_model','User_model', 'Log_model'));
		$current_user = $this->authorize->current_user();
		$data['card_count'] = $this->User_card_model->get_cards_count($current_user);
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$count = $this->input->post("count");
			$nickname = $this->input->post("nickname");
			if (empty($count) || $count <= 0 || empty($nickname)) {
				$data['error_message'] = "请确认您已经填写数据,并且正确";
			} else if ($count > $data['card_count']) {
				$data['error_message'] = "您剩余的行动卡不够";
			} else {
				$receiver = $this->User_model->find_user_by_nick($nickname);
				if (empty($receiver)) {
					$data['error_message'] = "行动卡接收者不存在";
				} else {
					$this->User_card_model->transfer_card($current_user, $receiver['id'],  $count);
					$log = array('type' => 'transfer', 'created_by' => $current_user, 'created' => date("Y-m-d H:i:s")
								,'params' => json_encode(array('receiver_id' => $receiver['id'], 'count' => $count)));
					$this->Log_model->add($log);
					$s_data = array('count' => $count, 'receiver' => $receiver, 'card_count' => ($data['card_count']- $count));
					$this->load->view('buy/transfer_success', $s_data);
					return;
				}
			}
			$data['nickname'] = $nickname;
			$data['count'] = $count;
			$this->load->view('buy/transfer', $data);
		} else {
			
			$this->load->view('buy/transfer', $data);
		}
		
	}
	/**
	 * 支付宝
	 */
	function by_alipay() {
		$this->load->view('buy/by_alipay');
	}
	
	/**
	 * 柜台转账
	 */
	function by_remittance() {
		$this->load->view('buy/by_remittance');
	}
}